package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private DishService dishService;

    /**
     * 新增菜品 （需要插入到菜品表和口味表）
     *
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional  //注解事务管理
    public void add(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //向菜品表插入
        dishMapper.insert(dish);
        //获取菜品表主键的值
        Long dishId = dish.getId();

        //向口味表插入,向每一个口味表都插入菜品的主键
        //TODO 此处用到拉姆他表达式，方法引用也可以实现
        List<DishFlavor> dishFlavorList = dishDTO.getFlavors();
        if (dishFlavorList != null && dishFlavorList.size() > 0) {
            dishFlavorList.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.insert(dishFlavorList);
        }

    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult queryByPage(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.queryByPage(dishPageQueryDTO.getName(), dishPageQueryDTO.getCategoryId());

        //返回pageResult
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        return pageResult;
    }

    /**
     * 批量删除菜品
     *
     * @param list
     * @return
     */
    @Transactional//事务
    @Override
    public void deleteByIds(List<Long> list) {
        //1.如果菜品起售中不能删除
        List<Long> ids = dishMapper.queryStatusByIds(list);
        if (ids != null && ids.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //2.如果当前菜品关联了套餐不能删除
        ids = setmealMapper.queryByDishIds(list);
        if (ids != null && ids.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品对应的口味
        dishFlavorMapper.deleteByIds(list);
        //删除菜品
        dishMapper.deleteByIds(list);

    }

    /**
     * 菜品起售、停售
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    public void enableOrDisable(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.update(dish);
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> queryByCategoryId(Long categoryId) {
        List<Dish> dishList = dishMapper.queryByCategoryId(categoryId);
        return dishList;
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO queryById(Long id) {
        Dish dish = dishMapper.queryById(id);
        //菜品对应的口味
        List<DishFlavor> dishFlavorList = dishFlavorMapper.queryBydishId(id);
        //封装到DishVO
        DishVO dishVO = new DishVO();
        //复制
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     * @return
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {

        Dish dish = dishMapper.queryById(dishDTO.getId());
        if (dish == null) {
            throw new BaseException("菜品为空");
        }
        //删除菜品原有的口味表
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //插入修改后的口味表
        if (dishDTO.getFlavors() != null && dishDTO.getFlavors().size() > 0) {
            List<DishFlavor> flavors = dishDTO.getFlavors();
            //遍历存入菜品的id
            flavors.forEach(flavor -> {
                flavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insert(flavors);
            //修改菜品表信息
        }

        Dish newDish = new Dish();
        BeanUtils.copyProperties(dishDTO, newDish);
        dishMapper.update(newDish);

    }

    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
